package feces.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import com.google.gson.reflect.TypeToken;

import feces.model.Product;
import feces.model.PurchaseOrder;
import feces.model.PurchaseOrderProduct;
import feces.model.Storehouse;
import feces.model.StorehouseIn;
import feces.model.StorehouseProduct;
import feces.utility.JSON;
import feces.utility.Utility;

/**
 * 购货单管�?
 * @author 韩少华
 * @author 李则宇
 */
public class PurchaseOrderServlet extends RESTfulServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6053232863477249449L;


	/**
	 * 字典
	 *
	 */
	@NoArgsConstructor(access = AccessLevel.PRIVATE)
	public static final class Dictonary {
		public static final String ID = "id";

		public static final String PRODUCTS = "products";
		
		public static final String DATE = "date";

		public static final String IS_FINISHED = "is_finished";
		
		public static final Integer CentralStorehouseID = 81;
	}
	/**
	 * 响应POST请求
	 * 创建购货单
	 * 
	 */
	@SuppressWarnings("unused")
	@Override
	protected Response<PurchaseOrder> responseCreate(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		final PurchaseOrder purOrder = new PurchaseOrder();
		final PurchaseOrderProduct pop=new PurchaseOrderProduct();
		purOrder.setCreation_date(java.sql.Date.valueOf(request.getParameter("date")));
		purOrder.setIs_finished(Utility.toInteger(request.getParameter("finish")));
		final List<PurchaseOrderProduct> lspro= JSON.from(
			request.getParameter("pro_list"), new TypeToken<List<PurchaseOrderProduct>>(){}.getType()
		);
		purOrder.setProducts(lspro);
		if (purOrder.isValid()) {
			boolean result = doTransaction(new Runnable(){

				@Override
				public void run() {
					add(purOrder);
					for (PurchaseOrderProduct pop : lspro) {
					pop.setProduct(find(Product.class,pop.getProduct_id()));
					pop.setOrder_id(purOrder.getId());
					}
					update(purOrder);
				}
			});
			if (result) {
				return succeed(purOrder);
			}
			return exception(null);
		}
		return failed(null);
	}
	/**
	 * 响应get请求
	 * 获取购货单
	 * 
	 */
	@Override
	protected Response<List<PurchaseOrder>> responseRead(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		return succeed(findAll(PurchaseOrder.class));
	}
	
	
	/**
	 * 响应PUT请求
	 * 修改订单状态
	 * 
	 * @return 操作结果
	 */
	@SuppressWarnings({ "cast" })
	@Override
	protected Response<Boolean> responseUpdate(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		@SuppressWarnings("unchecked")
		final List<String> parameter = (List<String>)JSON.from(request.getParameter("ids"),List.class);
		if (parameter == null) {
			return invalid(false);
		}
		boolean result = doTransaction(new Runnable(){
			
			@Override
			public void run() {
				for(int z=0;z<parameter.size();z++){
					Integer id = Utility.toInteger(parameter.get(z));
					PurchaseOrder purchaseOrder = find(PurchaseOrder.class, id);
					purchaseOrder.setIs_finished(1);		
					update(purchaseOrder);
					List<PurchaseOrderProduct> purchaseOrderProducts = purchaseOrder.getProducts();
					for(int pro=0;pro<purchaseOrderProducts.size();pro++){
						Integer proId = purchaseOrderProducts.get(pro).getProduct().getId();
						StorehouseProduct storehouseProduct = find(StorehouseProduct.class, new StorehouseProduct.PrimaryKey(Dictonary.CentralStorehouseID,proId));
						Integer current = storehouseProduct.getQuantity()+purchaseOrderProducts.get(pro).getReal_quantity();
						storehouseProduct.setQuantity(current);
						update(storehouseProduct);
						//生成入库记录
						StorehouseIn storehouseIn = new StorehouseIn();
						storehouseIn.setProduct(purchaseOrderProducts.get(pro).getProduct());
						storehouseIn.setStorehouse(find(Storehouse.class, Dictonary.CentralStorehouseID));
						storehouseIn.setAmount(purchaseOrderProducts.get(pro).getReal_quantity());
						add(storehouseIn);
					}
				}
			}
		});
		return result ? succeed(true) : exception(false);
	}
}
